import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getTokenInfo, hasToken, removeTokenInfo, setTokenInfo } from './storage'
import history from './history'
import store from '@/store'
import { logout, saveToken } from '@/store/actions/login'

const baseURL = 'http://toutiao.itheima.net/v1_0'
const http = axios.create({
	baseURL: baseURL,
	timeout: 50000,
})

http.interceptors.request.use((config) => {
	if (hasToken()) {
		const token = getTokenInfo().token || ''
		config.headers.Authorization = `Bearer ${token}`
	}
	return config
})

http.interceptors.response.use(
	(response) => {
		return response.data
	},
	async (error) => {
		// 网络问题
		if (!error.response) {
			Toast.info('网络繁忙, 请稍后重试')
			// 要返回Promise.reject(error), 不让外面即使错误还会向下执行
			return Promise.reject(error)
		}

		// 网络没问题, 后台返回数据
		const { response } = error
		if (response.status !== 401) {
			Toast.info(response.data.message)
			return Promise.reject(error)
		}

		// 网络没问题, 且是401 token失效的问题
		// 1. 有没有刷新token
		const { token, refresh_token } = getTokenInfo()
		if (!refresh_token) {
			// 这里不能使用useHistory, hoots指定在自定义组件中使用
			history.push({
                pathname: '/login',
				state: {
					from: history.location.pathname
				}
            })
            return Promise.reject(error)
		}
        // 是401, 且有刷新token
		// 尝试发送请求, 获取新的token, 注意: 刷新token发送请求, 不能使用封装的axios
        try {
            const res = await axios.put(`${baseURL}/authorizations`, null, {
                headers: {
                    Authorization: `Bearer ${refresh_token}`,
                },
            })

            const tokeInfo = {
                refresh_token,
                token: res.data.data.token
            }

            setTokenInfo(tokeInfo)
            store.dispatch(saveToken(tokeInfo))

			// token刷新后, 重新把最开始错误的请求重复
            return http(error.config)
        } catch (error) {
			// 刷新token失败, 例如refresh_token也过期了
            removeTokenInfo()
            store.dispatch(logout())

            history.replace('/login',{
                from: history.location.pathname || 'login'
            })

			Toast.info('登录信息失效, 请重新登录')
            return Promise.reject(error)
        }
	}
)

export default http
